// vite-plugin-scss-vars.js
import { writeFileSync, mkdirSync, existsSync } from 'fs';
import { resolve, dirname } from 'path';

export default function scssVarsPlugin(options) {
  // 默认配置
  const {
    outputPath = 'src/styles/generated-vars.scss', // 生成的 SCSS 文件路径
    getVariables = () => ({}) // 获取变量的函数（需用户自定义）
  } = options;
  const generateVars = () => {
    const variables = getVariables();
    let scssContent = '';
    for (const [key, value] of Object.entries(variables)) {
      scssContent += `${key}: ${value};\n`;
    }

    // 获取完整的输出路径
    const fullOutputPath = resolve(process.cwd(), outputPath);
    const outputDir = dirname(fullOutputPath);

    // 检查目录是否存在，不存在则创建
    if (!existsSync(outputDir)) {
      mkdirSync(outputDir, { recursive: true });
    }

    // 写入文件
    writeFileSync(fullOutputPath, scssContent);
    console.log('SCSS variables generated!');
  };
  return {
    name: 'vite-plugin-scss-vars',
    // 在服务器启动时生成变量文件
    configureServer() {
      // 初始化生成
      generateVars();
    }
  };
}
